import { useEffect, useState } from 'react'
const AdmZip = require('adm-zip')
import { MyFile } from '../../type'
const nodePath = require('path')

export function useGetFiles(path: string): [MyFile[]] {
  const [files, setFiles] = useState<MyFile[]>([])

  function gen(name: string, _files: MyFile[]): void {
    const spName = name.split('/')

    let path = ''
    let temp = _files
    for (let i = 0; i < spName.length; i++) {
      path += spName[i] + (i < spName.length - 1 ? '/' : '')

      const index = temp.findIndex((t) => t.path === path)

      if (index === -1) {
        const isDirectory = spName.length > 1 && i < spName.length - 1
        const children: MyFile[] = []

        let insertIndex = temp.length

        if (isDirectory) {
          const isFileIndex = temp.findIndex((t) => !t.isDirectory)

          if (isFileIndex !== -1) {
            insertIndex = isFileIndex
          }
        }
        temp.splice(insertIndex, 0, {
          path,
          isDirectory,
          children
        })
        temp = children
      } else {
        temp = temp[index].children!
      }
    }
  }

  useEffect(() => {
    if (path) {
      const admZip = new AdmZip(path)

      const baseName = nodePath.basename(path)
      const _files: MyFile[] = [
        {
          isDirectory: true,
          path: baseName,
          children: []
        }
      ]
      admZip.getEntries().forEach((entry) => {
        gen(entry.entryName, _files[0].children!)
      })

      setFiles(_files)
    }
  }, [path])

  return [files]
}
